package top.lyjwn.ajui.activity;

import androidx.appcompat.app.AppCompatActivity;
import top.lyjwn.ajui.AJUIApplication;
import top.lyjwn.ajui.R;
import top.lyjwn.ajui.base.BaseActivity;
import top.lyjwn.ajui.base.ITitleBar;
import top.lyjwn.ajui.data.Content;
import top.lyjwn.ajui.data.Message;
import top.lyjwn.ajui.data.Receiver;
import top.lyjwn.ajui.data.Sender;
import top.lyjwn.ajui.data.SenderMessage;
import top.lyjwn.ajui.listener.SoftKeyBoardListener;
import top.lyjwn.ajui.network.HttpUtil;
import top.lyjwn.ajui.network.OnCallback;
import top.lyjwn.ajui.receiver.ChatDialogReceiver;
import top.lyjwn.ajui.test.ChatContentAdapter;
import top.lyjwn.ajui.test.UserUtil;
import top.lyjwn.ajui.util.LogUtil;
import top.lyjwn.ajui.util.UrlUtil;
import top.lyjwn.ajui.widget.botton.RoundButton;
import top.lyjwn.ajui.widget.recycler.RecyclerVerticalView;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 聊天对话框
 *
 * @author luoyujie
 */
public class ChatDialogActivity extends BaseActivity {

    private LinearLayout chat_dialog_bottom;

    private ExecutorService executor = Executors.newFixedThreadPool(1);

    private ITitleBar iTitleBar;

    /**
     * 聊天窗口接收器
     */
    private ChatDialogReceiver chatDialogReceiver;

    /**
     * 聊天内容
     */
    private RecyclerVerticalView chat_dialog_dialog;

    /**
     * 聊天内容适配器
     */
    private ChatContentAdapter chatContentAdapter;

    /**
     * 输入内容
     */
    private EditText chat_dialog_input;

    /**
     * 发送按钮
     */
    private RoundButton chat_dialog_send;

    /**
     * 对方的用户id
     */
    private String opposite_user_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        chat_dialog_bottom = findViewById(R.id.chat_dialog_bottom);
        iTitleBar = findViewById(R.id.iTitleBar);
        chat_dialog_input = findViewById(R.id.chat_dialog_input);
        chat_dialog_send = findViewById(R.id.chat_dialog_send);
        chat_dialog_dialog = findViewById(R.id.chat_dialog_dialog);
        Intent intent = getIntent();
        String opposite_user_name = intent.getStringExtra("opposite_user_name");
        opposite_user_id = intent.getStringExtra("opposite_user_id");
        iTitleBar.setTitle(opposite_user_name);
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {

            @Override
            public void keyBoardShow(int height) {
                Log.i("软键盘", "键盘显示 高度" + height);
                int left = chat_dialog_bottom.getPaddingLeft();
                int top = chat_dialog_bottom.getPaddingTop();
                int right = chat_dialog_bottom.getPaddingRight();
                //软键盘的高度要减掉常用语内容的高度
                chat_dialog_bottom.setPadding(left, top, right, height);
            }

            @Override
            public void keyBoardHide(int height) {
                Log.i("软键盘", "键盘隐藏 高度" + height);
                int left = chat_dialog_bottom.getPaddingLeft();
                int top = chat_dialog_bottom.getPaddingTop();
                int right = chat_dialog_bottom.getPaddingRight();
                chat_dialog_bottom.setPadding(left, top, right, 0);
            }
        });
        //注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction("top.lyjwn.ajui.receiver.ChatDialogReceiver");
        chatDialogReceiver = new ChatDialogReceiver(this);
        chatContentAdapter = new ChatContentAdapter();
        chat_dialog_dialog.setAdapter(chatContentAdapter);
        //注册接收器
        registerReceiver(chatDialogReceiver, filter);
        chat_dialog_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (chat_dialog_input.getText().toString().length()>0){
                    SenderMessage senderMessage = new SenderMessage(0);
                    senderMessage.setContent(chat_dialog_input.getText().toString());
                    senderMessage.setReceiver(opposite_user_id);
                    String jsonString = JSONObject.toJSONString(senderMessage);
                    LogUtil.d("发送消息", jsonString);
                    if (AJUIApplication.getChatWebSocket().send(jsonString)) {
                        Content content = new Content();
                        content.setText(chat_dialog_input.getText().toString());
                        Sender sender = new Sender(UserUtil.getUser().getId());
                        Receiver receiver = new Receiver(senderMessage.getReceiver());
                        Message message = new Message();
                        message.setType(Message.TEXT);
                        message.setContent(content);
                        message.setMessageClientId(senderMessage.getMessageClientId());
                        message.setReceiver(receiver);
                        message.setSender(sender);
                        List<Message> messages = new ArrayList<>();
                        messages.add(message);
                        chatContentAdapter.add(messages);
                        chat_dialog_input.setText("");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                chat_dialog_dialog.smoothScrollToPosition(chatContentAdapter.getItemCount());
                            }
                        });
                    }
                }
            }
        });
        //获取聊天记录
        HttpUtil.get(UrlUtil.HOST + "/chat/find/by/myUserId/and/oppositeUserId?myUserId="+UserUtil.getUser().getId()+"&oppositeUserId="+opposite_user_id+"&page=1&limit=20", new OnCallback() {
            @Override
            public void onResponse(boolean done, Integer code, String msg, String data) {
                if (done) {
                    JSONObject jsonObject = JSONObject.parseObject(data);
                    if (jsonObject.getLongValue("total") > 0) {
                        List<Message> messages = jsonObject.getJSONArray("list").toJavaList(Message.class);
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                chatContentAdapter.refresh(messages);
                                chat_dialog_dialog.smoothScrollToPosition(chatContentAdapter.getItemCount());
                            }
                        });
                    }
                }
            }
        });
    }

    public void receiverMessage(Message message) {
        List<Message> messages = new ArrayList<>();
        messages.add(message);
        chatContentAdapter.add(messages);
        handler.post(new Runnable() {
            @Override
            public void run() {
                chat_dialog_dialog.smoothScrollToPosition(chatContentAdapter.getItemCount());
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(chatDialogReceiver);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_acvitity_chat_dialog;
    }
}
